<?php



class Router
{
    var $params;
    var $render_type;
    var $urls;
    
    public function Router () {
        //$this->render_type = JXRRT_NONE;
        $this->urls = array();
    }
    /*
     * Get Analyzer result.
     */
    public function getController () {
        return $this->params["controller"];
    }
    public function getAction () {
        return $this->params["action"];
    }
    public function getParameters () {
        return $this->params;
    }
    public function getStaticTemplate () {
        return $this->param["template"];
    }
    /*
     * Append YAML File
     */
    public function appendFile ($fname) {
        $urls = Config::loadFile($fname);

        if ($urls) {
            $this->urls = array_merge($this->urls, $urls);
        }

    }
    
    /*
     * Analyse url
     * @param string $url
     * @return Boolean
     */
    public function analyze ($url) {
        function __rgx_filter($s) {
            $s = str_replace('/', '\/', $s);
            return '/'.$s.'/i';
        }
        $this->param = array();
        foreach( $this->urls as $ptn ) {
            if (preg_match_all(__rgx_filter($ptn["pattern"]), $url, $reg_result)) {
                foreach($ptn as $key=>$value) {
                    if ($key != "pattern") {
                        $this->params[$key] = $value;
                    }
                }
                foreach($reg_result as $key=>$value) {
                    $this->params[$key] = $value[0];
                }
                return true;
            }
            
        }
        return false;
    }
    /**
     * do route
     * @param Request $request
     * @param Response $response
     * @return Router
     */
    public function route (Request $request, Response $response) {
        $url = $request->url;
        $this->analyze($url);
        $request->controller = $this->getController();
        $request->action = $this->getAction();
        $request->params = $this->getParameters();
    }
}

